package com.eshop.modules.quartz.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.context.annotation.Bean;
import org.quartz.spi.JobFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.quartz.Scheduler;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class QuartzConfig
{
    @Bean(name = { "scheduler" })
    public Scheduler scheduler(final QuartzJobFactory quartzJobFactory) throws Exception {
        final SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setJobFactory((JobFactory)quartzJobFactory);
        factoryBean.afterPropertiesSet();
        final Scheduler scheduler = factoryBean.getScheduler();
        scheduler.start();
        return scheduler;
    }
    
    @Component("quartzJobFactory")
    public static class QuartzJobFactory extends AdaptableJobFactory
    {
        private final AutowireCapableBeanFactory capableBeanFactory;
        
        public QuartzJobFactory(final AutowireCapableBeanFactory capableBeanFactory) {
            this.capableBeanFactory = capableBeanFactory;
        }
        
        protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
            final Object jobInstance = super.createJobInstance(bundle);
            this.capableBeanFactory.autowireBean(jobInstance);
            return jobInstance;
        }
    }
}
